package com.ruoyi.proposal.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.proposal.domain.Proposal;
import com.ruoyi.proposal.dto.ProposalDTO;
import com.ruoyi.proposal.dto.ProposalQueryDTO;
import com.ruoyi.proposal.service.ProposalService;
import com.ruoyi.proposal.vo.ProposalVO;
import com.sun.tools.jconsole.JConsolePlugin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * 提案审核评分API控制器
 * 对应前端audit.vue页面
 */
@RestController
@RequestMapping("/proposal/score")
public class ProposalAuditController extends BaseController {

    @Autowired
    private ProposalService proposalService;

    /**
     * 查询待打分提案
     * 对应前端audit.vue中的loadProposals方法
     * @param queryDTO 查询条件
     * @return 响应结果
     */
    @PreAuthorize("@ss.hasPermi('proposal:audit:list')")
    @GetMapping("/list")
    public TableDataInfo listScoreProposals(ProposalQueryDTO queryDTO) {
        return proposalService.findScoreProposalList(queryDTO);
    }


    /**
     * 提交评分
     * 对应前端audit.vue中的submitForm方法
     * @param proposal 提案对象
     * @return 响应结果
     */
    @PreAuthorize("@ss.hasPermi('proposal:audit:edit')")
    @Log(title = "评分管理", businessType = BusinessType.UPDATE)
    @PostMapping
    public AjaxResult submitScore(@RequestBody Proposal proposal) {
        try {
            // 如果没有提供详细的评分项，则计算总分
            if (proposal.getSupervisorTotalScore() == null &&
                    (proposal.getSupervisorCompleteness() != null ||
                            proposal.getSupervisorApplicability() != null ||
                            proposal.getSupervisorInnovation() != null ||
                            proposal.getSupervisorSafetyEnvironment() != null ||
                            proposal.getSupervisorQuality() != null ||
                            proposal.getSupervisorEfficiency() != null ||
                            proposal.getSupervisorCost() != null ||
                            proposal.getSupervisorPromotion() != null ||
                            proposal.getSupervisorEffort() != null)) {
                // 计算主管总分
                int supervisorTotal = calculateTotalScore(
                        proposal.getSupervisorCompleteness(),
                        proposal.getSupervisorApplicability(),
                        proposal.getSupervisorInnovation(),
                        proposal.getSupervisorSafetyEnvironment(),
                        proposal.getSupervisorQuality(),
                        proposal.getSupervisorEfficiency(),
                        proposal.getSupervisorCost(),
                        proposal.getSupervisorPromotion(),
                        proposal.getSupervisorEffort()
                );
                proposal.setSupervisorTotalScore(supervisorTotal);
            }

            if (proposal.getManagerTotalScore() == null &&
                    (proposal.getManagerCompleteness() != null ||
                            proposal.getManagerApplicability() != null ||
                            proposal.getManagerInnovation() != null ||
                            proposal.getManagerSafetyEnvironment() != null ||
                            proposal.getManagerQuality() != null ||
                            proposal.getManagerEfficiency() != null ||
                            proposal.getManagerCost() != null ||
                            proposal.getManagerPromotion() != null ||
                            proposal.getManagerEffort() != null)) {
                // 计算经理总分
                int managerTotal = calculateTotalScore(
                        proposal.getManagerCompleteness(),
                        proposal.getManagerApplicability(),
                        proposal.getManagerInnovation(),
                        proposal.getManagerSafetyEnvironment(),
                        proposal.getManagerQuality(),
                        proposal.getManagerEfficiency(),
                        proposal.getManagerCost(),
                        proposal.getManagerPromotion(),
                        proposal.getManagerEffort()
                );
                proposal.setManagerTotalScore(managerTotal);
            }

            if (proposal.getCommitteeTotalScore() == null &&
                    (proposal.getCommitteeCompleteness() != null ||
                            proposal.getCommitteeApplicability() != null ||
                            proposal.getCommitteeInnovation() != null ||
                            proposal.getCommitteeSafetyEnvironment() != null ||
                            proposal.getCommitteeQuality() != null ||
                            proposal.getCommitteeEfficiency() != null ||
                            proposal.getCommitteeCost() != null ||
                            proposal.getCommitteePromotion() != null ||
                            proposal.getCommitteeEffort() != null)) {
                // 计算委员会总分
                int committeeTotal = calculateTotalScore(
                        proposal.getCommitteeCompleteness(),
                        proposal.getCommitteeApplicability(),
                        proposal.getCommitteeInnovation(),
                        proposal.getCommitteeSafetyEnvironment(),
                        proposal.getCommitteeQuality(),
                        proposal.getCommitteeEfficiency(),
                        proposal.getCommitteeCost(),
                        proposal.getCommitteePromotion(),
                        proposal.getCommitteeEffort()
                );
                proposal.setCommitteeTotalScore(committeeTotal);
            }

            // 计算奖金
            // 按照主管 -> 经理 -> 委员会的顺序，取最后一个有值的评分为最终结果
            Integer finalScore = null;

            if (proposal.getCommitteeTotalScore() != null) {
                finalScore = proposal.getCommitteeTotalScore();
            } else if (proposal.getManagerTotalScore() != null) {
                finalScore = proposal.getManagerTotalScore();
            } else if (proposal.getSupervisorTotalScore() != null) {
                finalScore = proposal.getSupervisorTotalScore();
            }

            // 如果三个评分都为null，则奖金为0
            if (finalScore == null) {
                proposal.setBonus(BigDecimal.ZERO);
            } else {
                // 根据新的奖级规则计算奖金
                BigDecimal bonus = BigDecimal.ZERO;

                if (finalScore >= 80) {
                    bonus = new BigDecimal("1200");
                } else if (finalScore >= 70) {
                    bonus = new BigDecimal("900");
                } else if (finalScore >= 60) {
                    bonus = new BigDecimal("600");
                } else if (finalScore >= 50) {
                    bonus = new BigDecimal("450");
                } else if (finalScore >= 40) {
                    bonus = new BigDecimal("300");
                } else if (finalScore >= 30) {
                    bonus = new BigDecimal("250");
                } else if (finalScore >= 20) {
                    bonus = new BigDecimal("150");
                } else if (finalScore >= 10) {
                    bonus = new BigDecimal("50");
                } else if (finalScore >= 5) {
                    bonus = new BigDecimal("20");
                } else if (finalScore >= 1) {
                    bonus = new BigDecimal("5");
                } else {
                    bonus = BigDecimal.ZERO;
                }

                proposal.setBonus(bonus);
            }


            // 调用服务提交评分
            proposalService.submitScore(convertToDTO(proposal));
            return AjaxResult.success("评分提交成功");
        } catch (Exception e) {
            return AjaxResult.error("评分提交失败: " + e.getMessage());
        }
    }

    /**
     * 计算总分
     * @param scores 评分数组
     * @return 总分
     */
    private int calculateTotalScore(Integer... scores) {
        int total = 0;
        for (Integer score : scores) {
            if (score != null) {
                total += score;
            }
        }
        return total;
    }

    /**
     * 将Proposal对象转换为ProposalDTO
     * @param proposal 提案对象
     * @return 提案DTO对象
     */
    private com.ruoyi.proposal.dto.ProposalDTO convertToDTO(Proposal proposal) {
        com.ruoyi.proposal.dto.ProposalDTO dto = new com.ruoyi.proposal.dto.ProposalDTO();
        org.springframework.beans.BeanUtils.copyProperties(proposal, dto);
        return dto;
    }
}